<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 *  Partner Controller
 *
 * @package XGO CMS v2.0
 * @subpackage partner
 * @author Manh Nguyen - 08/08/2012
 * @link http://sunsoft.vn
 */
class Partner extends CI_Controller {

    /**
     * Contrust class
     *
     * @access public
     */
    public function __construct() {
        parent::__construct();

		$this->load->library('smarty3', '', 'smarty');
        
        require_once(APPPATH . 'modules/backend/autoload.php');        
        
        $this->load->library('login_manager');
        require_once(APPPATH . 'modules/backend/info.php');

        $this->login_manager->check_role('partner');
        $this->load->language('backend');
        $this->smarty->assign('language', $this->lang);
        $this->smarty->assign('message', $this->session->flashdata('message'));
        $this->smarty->assign('error_message', $this->session->flashdata('error_message'));
    }

    /**
     * index function, show jquery grid
     *
     * @access public
     * @param null
     * @return void
     */
    function index() {
        $parameters = $this->uri->ruri_to_assoc();

        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
            if ($id > 0) {
                $this->session->set_userdata('search_id', $id);
            }
        }

        $css_files = array(base_url() . 'data/jscripts/jqgrid/css/ui.jqgrid.css');

        $js_files = array(
            base_url() . 'data/jscripts/jqgrid/i18n/grid.locale-vi.js',
            base_url() . 'data/jscripts/jqgrid/jquery.jqGrid.min.js'
        );

        require_once(APPPATH . 'modules/backend/history.php');
        $partner = new Partner_model();

        //load parameters and initialize grid
        $jqgrid = array();

        $jqgrid['id'] = 'jqgrid';
        $jqgrid['pager'] = 'pagered';
        $jqgrid['caption'] = $partner->localize_label('manager');
        $jqgrid['url_metadata'] = site_url($this->router->directory . 'partner/jqgrid_jsoninit');
        $jqgrid['url_data'] = site_url($this->router->directory . 'partner/jqgrid_jsondata');
        $jqgrid['url_create'] = site_url($this->router->directory . 'partner/create');
        $jqgrid['url_edit'] = site_url($this->router->directory . 'partner/edit');
        $jqgrid['url_delete'] = site_url($this->router->directory . 'partner/delete');

        $this->smarty->assign('jqgrid', $jqgrid);

        $jqgrid_init = $this->smarty->get_contents('template/backend/js/jqgrid');
        $js_text = array($jqgrid_init);

        $this->smarty->assign('css_files', $css_files);
        $this->smarty->assign('js_files', $js_files);
        $this->smarty->assign('js_text', $js_text);
        $this->smarty->assign('title', $partner->localize_label('manager'));

        // view
        $this->smarty->view('backend/partner/jqgrid', 'grid');
        $this->smarty->display('template/backend/admin');
    }

    /**
     * Create partner
     *
     * @access public
     */
    public function create() {
        $partner 		= new Partner_model();
        $language    	= new Language_model();
        
        $this->smarty->assign('language', $language);
        $this->smarty->assign('partner', $partner);

        if ($this->input->server('REQUEST_METHOD') === 'GET') {
            $this->smarty->view('backend/partner/edit', 'main_content');
            $this->smarty->display('template/backend/admin');
        } else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('name', $partner->localize_label('name'), 'trim|required|max_length[150]');
            $this->form_validation->set_rules('code', $partner->localize_label('code'), 'trim|required|max_length[150]');

            if ($this->form_validation->run() == TRUE) {
                $partner = new Partner_model();
                $this->_save(site_url('auth/partner'), $partner);
            } else {
                $this->smarty->view('backend/partner/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    public function edit() {

        $partner = new Partner_model();
        $language    = new Language_model();
        
        $this->smarty->assign('language', $language);
        $this->smarty->assign('partner', $partner);

        if ($this->input->server('REQUEST_METHOD') === 'GET') {

            $parameters = $this->uri->ruri_to_assoc(3);

            if (isset($parameters['id'])) {
                $id = intval($parameters['id']);
            } else {
                $id = 0;
            }

            $partner->get_by_id($id);

            if ($partner->exists()) {                
                $this->smarty->view('backend/partner/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            } else {
                $this->session->set_flashdata('error_message', $this->lang->line('not_found')/* 'Bài viết này không tồn tại xin vui lòng kiểm tra lại.' */);
                redirect(site_url('auth/partner'));
            }
        } else {
            $this->load->library('form_validation');
            $this->form_validation->set_rules('name', $partner->localize_label('name'), 'trim|required|max_length[150]');
            $this->form_validation->set_rules('code', $partner->localize_label('code'), 'trim|required|max_length[150]');

            $id = $this->input->post('id');
            $partner->get_by_id($id);

            if ($this->form_validation->run() == TRUE) {
                $this->_save(site_url('auth/partner/'), $partner);
            } else {
                $this->smarty->assign('partner', $partner);
                $this->smarty->view('backend/partner/edit', 'main_content');
                $this->smarty->display('template/backend/admin');
            }
        }
    }

    private function _save($uri, $partner) {
        // Begin transaction
        $partner->trans_begin();

        $this->load->helper('news');

        $partner->name = $this->input->post('name');
        $partner->code = $this->input->post('code');
        $partner->homepage = $this->input->post('homepage');
        $partner->description = $this->input->post('description');
        $partner->language_id = $this->input->post('lang_id');

        $user = $this->login_manager->get_user();

        $now = date("Y:m:d H:i:s");

        if (!isset($partner->id)) {
            //created
            $partner->created = $now;
            $partner->creator_id = $user->id;
        } else {
            //edit
            $partner->updated = $now;
            $partner->editor_id = $user->id;
        }

        $partner->save();
        $exists = $partner->exists();
        // Attempt to save user
        // Check status of transaction
        if ($partner->trans_status() === FALSE) {
            // Transaction failed, rollback
            $partner->trans_rollback();

            // Add error message
            $u->error_message('transaction', 'The transaction failed to save (insert)');
        } else {
            // Transaction successful, commit
            $partner->trans_commit();

            if ($exists) {
                $this->session->set_flashdata('message', $partner->localize_label('edit_success')/* 'Đã cập nhật dữ liệu thành công.' */);
            } else {
                $this->session->set_flashdata('message', $partner->localize_label('create_success')/* 'Đã lưu dữ liệu thành công.' */);
            }
            redirect($uri);
        }
        // Show all errors
        $error = $partner->error->string;

        $this->session->set_flashdata('message', $error);
        redirect($uri);
    }

    /**
     * delete function, delete exists object
     *
     * @access public
     * @param id of object in url
     * @return void
     */
    public function delete() {

        $url = 'partner';

        $parameters = $this->uri->ruri_to_assoc();
        if (isset($parameters['id'])) {
            $id = intval($parameters['id']);
        } else {
            $id = 0;
        }

        if ($id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('no_access_direct'));
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }

        $partner = new Partner_model();
        $partner->where('id', $id);
        $partner->get(1);

        if ($partner->id <= 0) {
            //$this->session->set_flashdata('message', $this->lang->line('invalide_id'));
            $this->session->set_flashdata('error_message', $this->lang->line('not_found'));
            redirect($this->router->directory . $url);
        }

        $result = $partner->delete();
        if ($result === TRUE) {
            $this->session->set_flashdata('message', $partner->localize_label('delete_success'));
        } else {
            if ($result == -1) {
                $this->session->set_flashdata('message', $partner->localize_label('delete_news_first'));
            } elseif ($result == -2) {
                $this->session->set_flashdata('message', $partner->localize_label('delete_subpartner_first'));
            } else {
                $this->session->set_flashdata('message', $partner->localize_label('delete_fail'));
            }
        }
        redirect($this->router->directory . $url);
    }

    /**
     * init function, get para for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsoninit() {
        if (IS_AJAX) {
            $partner = new Partner_model();
            $metadata = $partner->jqgrid_metadata();
            echo json_encode($metadata);
        }
    }

    /**
     * data function, get data for jquery grid via ajax
     *
     * @access public
     * @param null
     * @return array in json encode
     */
    function jqgrid_jsondata() {
        if (IS_AJAX) {
            $search = $this->input->post('_search');
            $filters = json_decode($this->input->post('filters'));
            $order = $this->input->post('sidx');
            $order_direct = $this->input->post('sord');
            $page = intval($this->input->post('page'));
            $num_per_page = intval($this->input->post('rows'));

            $relative_search = array();

            $this->load->helper('jqgrid');

            $partner = jqgrid_search(new Partner_model(), $search, $filters, $order, $order_direct, $page, $num_per_page, $relative_search);

            $paged = $partner->paged;
            $responce = new Stdclass();
            $responce->page = $paged->current_page; //curent page
            $responce->total = $paged->total_pages; //total page
            $responce->records = $paged->total_rows; //total record
            $i = 0;

            foreach ($partner as $item) {
                $isLeaf = TRUE;
                $responce->rows[$i]['cell'] = array(
                    // Field
                    $item->id,
                    $item->name,
                    $item->code,
                    $item->homepage
                );
                $i++;
            }
            echo json_encode($responce);
        }
    }

}

/* End of file partner.php */
/* Location: ./system/application/controllers/backend/partner.php */